package com.wordlearning.app.controller;

import com.wordlearning.app.entity.Word;
import com.wordlearning.app.service.WordService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 单词管理控制器
 * 提供单词的CRUD操作和搜索功能的RESTful API端点
 */
@RestController
@RequestMapping("/words")
public class WordController {

    private final WordService wordService;

    /**
     * 构造函数，注入WordService依赖
     * @param wordService 单词服务接口实例
     */
    @Autowired
    public WordController(WordService wordService) {
        this.wordService = wordService;
    }

    /**
     * 创建新单词
     * API端点: POST /api/words/createWord
     * @param word 单词实体对象，包含单词内容、词性、释义等信息
     * @return 创建成功的单词对象和HTTP状态码201 Created；失败返回400 Bad Request
     */
    @PostMapping("/createWord")
    public ResponseEntity<Word> createWord(@RequestBody Word word) {
        try {
            Word createdWord = wordService.createWord(word);
            return new ResponseEntity<>(createdWord, HttpStatus.CREATED);
        } catch (IllegalArgumentException e) {
            return new ResponseEntity<>(null, HttpStatus.BAD_REQUEST);
        }
    }

    /**
     * 获取所有单词列表（支持分页）
     * API端点: GET /api/words/getAllWords?page={page}&pageSize={pageSize}
     * @param page 当前页码，默认为1
     * @param pageSize 每页记录数，默认为20
     * @return 单词列表和HTTP状态码200 OK
     */
    @GetMapping("/getAllWords")
    public ResponseEntity<List<Word>> getAllWords(@RequestParam(defaultValue = "1") int page,
                                                 @RequestParam(defaultValue = "20") int pageSize) {
        // 验证分页参数
        if (page < 1) page = 1;
        if (pageSize < 1 || pageSize > 100) pageSize = 20;
        
        List<Word> words = wordService.getAllWords(page, pageSize);
        return new ResponseEntity<>(words, HttpStatus.OK);
    }

    /**
     * 根据ID获取单个单词
     * API端点: GET /api/words/{id}
     * @param id 单词唯一标识符
     * @return 找到的单词对象和HTTP状态码200 OK；未找到返回404 Not Found
     */
    @GetMapping("/{id}")
    public ResponseEntity<Word> getWordById(@PathVariable("id") Long id) {
        return wordService.getWordById(id)
                .map(word -> new ResponseEntity<>(word, HttpStatus.OK))
                .orElseGet(() -> new ResponseEntity<>(HttpStatus.NOT_FOUND));
    }

    /**
     * 根据单词内容获取单词
     * API端点: GET /api/words/content/{content}
     * @param content 单词文本内容
     * @return 找到的单词对象和HTTP状态码200 OK；未找到返回404 Not Found
     */
    @GetMapping("/content/{content}")
    public ResponseEntity<Word> getWordByContent(@PathVariable("content") String content) {
        return wordService.getWordByContent(content)
                .map(word -> new ResponseEntity<>(word, HttpStatus.OK))
                .orElseGet(() -> new ResponseEntity<>(HttpStatus.NOT_FOUND));
    }

    /**
     * 更新单词信息
     * API端点: PUT /api/words/{id}
     * @param id 要更新的单词ID
     * @param word 包含更新信息的单词对象
     * @return 更新后的单词对象和HTTP状态码200 OK；未找到返回404 Not Found
     */
    @PutMapping("/{id}")
    public ResponseEntity<Word> updateWord(@PathVariable("id") Long id, @RequestBody Word word) {
        try {
            Word updatedWord = wordService.updateWord(id, word);
            return new ResponseEntity<>(updatedWord, HttpStatus.OK);
        } catch (IllegalArgumentException e) {
            return new ResponseEntity<>(null, HttpStatus.NOT_FOUND);
        }
    }

    /**
     * 删除单词
     * API端点: DELETE /api/words/{id}
     * @param id 要删除的单词ID
     * @return 成功删除返回204 No Content；未找到返回404 Not Found
     */
    @DeleteMapping("/{id}")
    public ResponseEntity<HttpStatus> deleteWord(@PathVariable("id") Long id) {
        try {
            wordService.deleteWord(id);
            return new ResponseEntity<>(HttpStatus.NO_CONTENT);
        } catch (IllegalArgumentException e) {
            return new ResponseEntity<>(HttpStatus.NOT_FOUND);
        }
    }

    /**
     * 根据关键词搜索单词
     * API端点: GET /api/words/search?keyword={keyword}
     * @param keyword 搜索关键词
     * @return 匹配的单词列表和HTTP状态码200 OK
     */
    @GetMapping("/search")
    public ResponseEntity<List<Word>> searchWords(@RequestParam("keyword") String keyword) {
        List<Word> words = wordService.searchWords(keyword);
        return new ResponseEntity<>(words, HttpStatus.OK);
    }

}